package com.central.apps.controller;

import com.central.app.service.HandlerService;
import com.central.common.util.ToolUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class TransferapplyheadController {
    @Autowired
    private HandlerService handlerService;

    @PostMapping("/transfer")
    public String transfer(@RequestBody Map<String,Object> params){
        String message ="子表无数据";
        String transfernum = MapUtils.getString(params,"transfernum");
        List<Map<String, Object>> bySql = handlerService.findBySql("select id from gq_transferapplydetail where transfernum ='" + transfernum + "'");
        if(!ToolUtil.isEmpty(bySql)){
            String id =MapUtils.getString(bySql.get(0),"id");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select assetnum from gq_assethead order by createtime desc  limit 1");
            String assetnum =MapUtils.getString(bySql1.get(0),"assetnum");
            String childNum =getNum(assetnum);
            handlerService.updateBySql("update gq_transferapplydetail set assetnum ='"+childNum+"' where id ="+id);
            for(int i=1;i<bySql.size();i++){
                Map<String, Object> map =bySql.get(i);
                String id1 =MapUtils.getString(map,"id");
                List<Map<String, Object>> bySql2 = handlerService.findBySql("select assetnum from gq_transferapplydetail order by assetnum desc limit 1");
                String assetnum1 =MapUtils.getString(bySql2.get(0),"assetnum");
                String childNum1 =getNum(assetnum1);
                handlerService.updateBySql("update gq_transferapplydetail set assetnum ='"+childNum1+"' where id ="+id1);
            }
            message ="子表资产编号已生成";
        }
        return message;
    }

    public String getNum(String assetnum){
        int num;
        if(assetnum.indexOf("0")!=-1){
            int index =assetnum.lastIndexOf("0");
            String assetnum1 =assetnum.substring(index+1);
            num =Integer.parseInt(assetnum1);
            num++;
        }else{
            String assetnum1=assetnum.substring(2);
            num =Integer.parseInt(assetnum1);
            num++;
        }
        String format = String.format("%05d", num);
        String result ="as"+format;
        return result;
    }

}
